package com.meiyu.live.net;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.meiyu.live.net.response.BaseResponse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class MultipartRequest<T> extends Request<T> {

    MultipartEntity mMultiPartEntity = new MultipartEntity();

    Map<String, String> mHeaders = new HashMap<String, String>();

    private final Response.Listener<T> mListener;
    public static final int TYPE_LIST = 1;
    public static final int TYPE_OBJECT = 0;
    private Class result;

    public MultipartRequest(String url, Class result, int type,
                            Response.Listener<T> listener, Response.ErrorListener errorListener) {
        super(Method.POST,
                url,
                errorListener);
        this.type = type;
        this.result = result;
        this.mListener = listener;
    }

    /**
     * @return
     */
    public MultipartEntity getMultiPartEntity() {
        return mMultiPartEntity;
    }

    private int type = 0;

    @Override
    public String getBodyContentType() {
        return mMultiPartEntity.getContentType().getValue();
    }

    public void addHeader(String key, String value) {
        mHeaders.put(key, value);
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return mHeaders;
    }

    @Override
    public byte[] getBody() {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            // multipart body
            mMultiPartEntity.writeTo(bos);
        } catch (IOException e) {
            Log.e("", "IOException writing to ByteArrayOutputStream");
        }
        return bos.toByteArray();
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        T parsedGSON = null;
        try {

            String jsonString = new String(response.data);
            Log.e("jsonString", jsonString);
//            String jsonString = new String(response.data,
//                    HttpHeaderParser.parseCharset(response.headers));
            parsedGSON = fromJson(jsonString, result);


        } catch (JsonSyntaxException je) {
            return Response.error(new ParseError(je));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.success(parsedGSON,
                HttpHeaderParser.parseCacheHeaders(response));
    }

    public T fromJson(String json, Class clazz) {
        Gson gson = new Gson();
        Type objectType;

//        if (type == TYPE_LIST) {
//            objectType = type(BaseListResponse.class, clazz);
//        } else {
        objectType = type(BaseResponse.class, clazz);
//        }

        return gson.fromJson(json, objectType);
    }

    public ParameterizedType type(final Class raw, final Type... args) {
        return new ParameterizedType() {
            public Type getRawType() {
                return raw;
            }

            public Type[] getActualTypeArguments() {
                return args;
            }

            public Type getOwnerType() {
                return null;
            }
        };
    }

    @Override
    protected void deliverResponse(T response) {
        if (mListener != null) {
            mListener.onResponse(response);
        }
    }

}
